package me.zhengjie.cron;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.RegisterAddressConfig;
import me.zhengjie.domain.ProInfoService;
import me.zhengjie.domain.UnbindingService;
import me.zhengjie.modbusTCP.UnbindingSplitTCP;
import me.zhengjie.modbusTCP.UnbindingTCP;
import me.zhengjie.util.AnalyseCodeScannerUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@RequiredArgsConstructor
public class UnbindingSplitCron {

    private final UnbindingService unbindingService;
    private final UnbindingSplitTCP unbindingSplitTCP;
    private final AnalyseCodeScannerUtil analyseCodeScannerUtil;

    /**
     * 一号拆解台分流
     */
    @Scheduled(fixedDelay = 1000)
    public void listenerUnbindingFlowTo() {
        try {
            Integer sensorValue = unbindingSplitTCP.readHoldingRegisters(RegisterAddressConfig.onOneUnbindingFlowSensor);
            String i = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onOneUnbindingFlowCodeScannerFirst);
            String j = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onOneUnbindingFlowCodeScannerSecond);

            String scannerValue = analyseCodeScannerUtil.analyseCodeScanner(i, j);
            log.info("1号拆解分流读值，传感器值：{}，扫码器值：{}", sensorValue, scannerValue);
            if (sensorValue != null && sensorValue == 1 && scannerValue != null) {

                unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onOneUnbindingFlowIfSuccessReadCode, 1, 5);
                // 分配流向
                Integer flowTo = unbindingService.getUnbindingStationFlowTo(scannerValue);
                if (flowTo != null) {
                    unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onOneUnbindingFlowTo, flowTo, 5);
                }
            }
        } catch (Exception e) {
            log.error("拆解一区分流定时器出错；{}", e.toString());
        }

    }

    /**
     * 二号拆解台分流
     */
    @Scheduled(fixedDelay = 1000)
    public void listenerUnbindingTwoFlowTo() {
        try {
            Integer sensorValue = unbindingSplitTCP.readHoldingRegisters(RegisterAddressConfig.onTwoUnbindingFlowSensor);
            String i = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onTwoUnbindingFlowCodeScannerFirst);
            String j = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onTwoUnbindingFlowCodeScannerSecond);
            String scannerValue = analyseCodeScannerUtil.analyseCodeScanner(i, j);
            log.info("2号拆解分流读值，传感器值：{}，扫码器值：{}", sensorValue, scannerValue);


            if (sensorValue != null && sensorValue == 1 && scannerValue != null) {

                unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onTwoUnbindingFlowIfSuccessReadCode, 1, 5);
                // 分配流向
                Integer flowTo = unbindingService.getUnbindingStationFlowTo(scannerValue);
                if (flowTo != null) {
                    unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onTwoUnbindingFlowTo, flowTo, 5);
                }
            }
        } catch (Exception e) {
            log.error("拆解二区分流定时器出错；{}", e.toString());
        }
    }
    /**
     * 一号拆解台分流
     */
    @Scheduled(fixedDelay = 1000)
    public void listenerUnbindingThreeFlowTo() {
        try {
            Integer sensorValue = unbindingSplitTCP.readHoldingRegisters(RegisterAddressConfig.onThreeUnbindingFlowSensor);
            String i = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onThreeUnbindingFlowCodeScannerFirst);
            String j = unbindingSplitTCP.readHoldingRegistersString(RegisterAddressConfig.onThreeUnbindingFlowCodeScannerSecond);
            String scannerValue = analyseCodeScannerUtil.analyseCodeScanner(i, j);
            log.info("3号拆解分流读值，传感器值：{}，扫码器值：{}", sensorValue, scannerValue);
            if (sensorValue != null && sensorValue == 1 && scannerValue != null) {
                unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onThreeUnbindingFlowIfSuccessReadCode, 1, 5);
                // 分配流向
                Integer flowTo = unbindingService.getUnbindingStationFlowTo(scannerValue);
                if (flowTo != null) {
                    unbindingSplitTCP.writeWithRetry(RegisterAddressConfig.onThreeUnbindingFlowTo, flowTo, 5);
                }
            }
        } catch (Exception e) {
            log.error("拆解三区分流定时器出错；{}", e.toString());
        }
    }
}









   // public void unbindingProduct(){
        /*try {
            *//*Integer sensorValue = TCPUtil.readHoldingRegisters(master,RegisterAddressConfig.unbindingSensor);
            String scannerValue = TCPUtil.readHoldingRegistersString(master,RegisterAddressConfig.unbindingCodeScanner);
            if (sensorValue == 1 && !scannerValue.isEmpty()){
                // 回报plc没有读到码
                TCPUtil.write(master,1111,0);
            }else if (sensorValue == 1){
                if (!scannerValue.equals(plcUnbindingRepository.findPlcUnbindingById(1).getContent())) {
                    plcService.updateUnbindingStationPalletCode(scannerValue, 1);
                    // 如果载盘码更新，开始记录拆解的生产信息
                    proInfoService.startUnbinding(LoginUtil.getLoginUser(), DateTime.now().toTimestamp(), scannerValue);
                }
            }
            Integer startButtonValue = TCPUtil.readHoldingRegisters(master,RegisterAddressConfig.unbindingStartSignal);*//*
            // 拆解区启动按钮信号
            Integer startButtonValue = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingStartSignal);
            if (startButtonValue == 1){
                // 读取扫码器寄存器地址，获得当前的载盘信息
                String i = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerFirst);
                String j = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerSecond);

                *//*String scannerValue = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScanner);*//*
                if (i!=null && j!=null){

                    i = new StringBuffer(i).reverse().toString();
                    j = new StringBuffer(j).reverse().toString();
                    String scannerValue = i.concat(j);

                    log.info("入库口plc读值，扫码器值：{}",scannerValue);
                    // 回报plc读码成功
                    unbindingTCP.write(1111,1);
                    // 解绑操作
                    unbindingService.unbinding(scannerValue);
                    // 记录拆解作业结束信息
                    proInfoService.finishUnbinding(DateTime.now().toTimestamp(), scannerValue);
                    // 回报plc没有读到码
                    unbindingTCP.write(1111,0);
                }else {
                    // 回报plc读码失败
                    unbindingTCP.write(1111,0);
                }
               *//* // 解绑操作
                unbindingService.unbinding(scannerValue);
                // 记录拆解作业结束信息
                proInfoService.finishUnbinding(DateTime.now().toTimestamp(), scannerValue);*//*
                //*productionInfoRepository.finishUnbindingProduction();
            }
        } catch (Exception e) {
            log.error("拆解区定时器出错，错误原因：{}",e.toString());
        }
*/

        /*Integer sensorValue = TCPUtil.readHoldingRegisters(master,RegisterAddressConfig.unbindingSensor);
        // 启动按钮信号，记录拆解工艺的结束时间
        int startButtonValue = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingButton);
        String palletCode = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.layUpCodeScanner);

        if (sensorValue == 1 && palletCode.isEmpty()) {

            // 如果识别到的载盘码发生变化, 更新新扫描到的载盘码
            if (!palletCode.equals(plcUnbindingRepository.findPlcUnbindingById(1).getContent())){
                plcService.updateUnbindingStationPalletCode(palletCode,1);
                // 如果载盘码更新，开始记录拆解的生产信息
                proInfoService.startUnbinding(LoginUtil.getLoginUser(),DateTime.now().toTimestamp(),palletCode);
                *//*productionInfoRepository.startUnbindingProduction(LoginUtil.getLoginUser(),DateTime.now().toTimestamp(),palletCode);*//*
            }
        }
        else if (startButtonValue == 1){
            int sensorValue = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingSensor);
            if (sensorValue == 0) return;
            else if (sensorValue == 1) {
                // 解绑操作
                unbindingService.unbinding(palletCode);
                // 记录拆解作业结束信息
                *//*productionInfoRepository.finishUnbindingProduction();*//*
                proInfoService.finishUnbinding(DateTime.now().toTimestamp(), palletCode);
                // 启动滚筒线
                unbindingTCP.write(RegisterAddressConfig.unbindingStartSignal,1,1);
            }
        }*/
    //}

    /**
     * 定时器定时读取
     * 拆解区扫码获取新的载盘信息
     * 更新plc新扫描到的载盘编码
     */

    //public void getNewPalletCode(){
        /*try {
            Integer sensorValue = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingSensor);
            String i = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerFirst);
            String j = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerSecond);


            if (sensorValue == 1 && (i==null || j==null)){
                // 回报plc没有读到码
                unbindingTCP.write(RegisterAddressConfig.unbindingIfSuccessReadCode,0);
            }else if (sensorValue == 1){

                i = new StringBuffer(i).reverse().toString();
                j = new StringBuffer(j).reverse().toString();
                String scannerValue = i.concat(j);
                log.info("入库口plc读值，传感器值：{}，扫码器值：{}",sensorValue,scannerValue);

                if (!scannerValue.equals(plcUnbindingRepository.findPlcUnbindingById(1).getContent())) {
                    plcService.updateUnbindingStationPalletCode(scannerValue, 1);
                    // 如果载盘码更新，开始记录拆解的生产信息
                    proInfoService.startUnbinding(LoginUtil.getLoginUser(), DateTime.now().toTimestamp(), scannerValue);
                    // 写入滚筒线的启动信号
                    unbindingTCP.write(RegisterAddressConfig.unbindingFlowTo,1);
                }
            }
        } catch (Exception e) {

        }*/
    //}


    /*public void unbindingStartCron(){
        try {
            Integer startSensor = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingStartSensor);

            if (startSensor!=null && startSensor == 1){
                String i = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerFirst);
                String j = unbindingTCP.readHoldingRegistersString(RegisterAddressConfig.unbindingCodeScannerSecond);
                *//*if (i == null || j == null){
                    // 回报plc没有读到码
                    unbindingTCP.write(RegisterAddressConfig.unbindingIfSuccessReadCode,2);
                }*//*
                if(i != null && j != null) {
                    unbindingTCP.writeWithRetry(RegisterAddressConfig.unbindingIfSuccessReadCode,1, 5);
                    i = new StringBuffer(i).reverse().toString();
                    j = new StringBuffer(j).reverse().toString();
                    String scannerValue = i.concat(j);
                    PlcUnbinding plcUnbinding = plcService.getUnbindingStationByIp(netConfig.getUnbindingPlcIp());
                    if (ObjectUtil.isEmpty(plcUnbinding)){
                        PlcUnbinding newPlcUnbinding = new PlcUnbinding();
                        newPlcUnbinding.setIp(netConfig.getUnbindingPlcIp());
                        newPlcUnbinding.setPort(502);
                        newPlcUnbinding.setContent(scannerValue);
                        plcUnbindingRepository.save(newPlcUnbinding);
                        // 开始记录拆解的生产信息
                        proInfoService.startUnbinding("admin", DateTime.now().toTimestamp(), scannerValue);
                    }else {
                        plcService.updateUnbindingStationByIp(scannerValue,netConfig.getUnbindingPlcIp());
                        // 开始记录拆解的生产信息
                        proInfoService.startUnbinding("admin", DateTime.now().toTimestamp(), scannerValue);
                    }
                }
            }
        } catch (Exception e) {
            log.error("拆解区plc1异常，错误原因：{}",e.getMessage());
        }
    }*/

/*

    public void unbindingSecondCron(){
        try {
            Integer endSensor = unbindingTCP.readHoldingRegisters(RegisterAddressConfig.unbindingEndSensor);
            if (endSensor !=null && endSensor == 1){
                unbindingTCP.writeWithRetry(RegisterAddressConfig.unbindingIfSuccessReadEndSensor,1, 5);
                ProductionInfo proInfo = proInfoService.getUnbindingProductionInfo();
                String palletCode = proInfo.getPalletCode();

                // 现场测试
                */
/*unbindingService.unbinding(palletCode);*//*

                // 记录拆解作业结束信息
                proInfoService.finishUnbinding(DateTime.now().toTimestamp(), palletCode);
            }
        } catch (Exception e) {
            log.error("拆解区plc2异常，错误原因：{}",e.getMessage());
        }
    }
}
*/
